using System;
using System.IO;
using System.Linq;
using SkiaSharp;
using UMC.Web;

namespace UMC.ITME.Activities
{
    [Apiumc("System", "Image", Desc = "上传图片", Weight = 0)]
    class SitePictureActivity : UMC.Web.Activities.SystemImageActivity
    {
        protected override void Picture(WebRequest request, WebResponse response)
        {
            var user = this.Context.Token.Identity();
            var key = this.AsyncDialog("Key", "Event");
            var imageKey = this.AsyncDialog("id", d =>
            {
                return this.DialogValue(this.Context.Token.UserId.ToString());
            });

            var size = this.AsyncDialog("size", "auto");
            var seq = this.AsyncDialog("index", "1");
            var webr = UMC.Data.WebResource.Instance();
            var media_id = this.AsyncDialog("media_id", g =>
            {
                if (request.IsApp)
                {
                    return Web.UIDialog.Create("File");
                }
                else
                {
                    var from = new Web.UIFormDialog() { Title = "图片上传" };

                    from.AddFile("选择图片", "media_id", String.Empty);
                    if (String.Equals("auto", size) == false)
                    {
                        from.AddFooter($"图片要求: {size}");
                    }
                    from.Submit("确认上传", $"{request.Model}.{request.Command}", "UI.Event");
                    return from;
                }
            });
            var type = this.AsyncDialog("type", "none");
            if (media_id.StartsWith("http://") == false && media_id.StartsWith("https://") == false)
            {
                if (media_id.Length > 3)
                {
                    media_id = Uri.UnescapeDataString(media_id);
                    var file = UMC.Data.Reflection.ConfigPath(String.Format("Static\\TEMP\\{0}", media_id.Substring(media_id.IndexOf('/', 2) + 1)));

                    if (System.IO.File.Exists(file))
                    {
                        media_id = $"file://{file}";

                    }
                    else
                    {
                        this.Prompt("未有上传的图片");
                    }

                }
                else
                {
                    var file = UMC.Data.Reflection.ConfigPath(String.Format("Static\\TEMP\\{0}", imageKey));

                    var image = new SKBitmap(200, 200);
                    type = "png";
                    var templateG = new SKCanvas(image);
                    using (SKPaint paint = new SKPaint())
                    {

                        var cs = new String[] { "#63b359", "#2c9f67", "#509fc9", "#5885cf", "#9062c0", "#d09a45", "#e4b138", "#ee903c", "#f08500", "#a9d92d", "#dd6549", "#cc463d", "#cf3e36", "#5E6671" };

                        paint.Color = SKColor.Parse(cs[Math.Abs(UMC.Data.Utility.IntParse(UMC.Data.Utility.Guid(imageKey, true).Value) % cs.Length)]);

                        templateG.DrawRect(SKRect.Create(new SKPoint(0, 0), new SKSize(200, 200)), paint);
                        using SKTypeface sKTypeface = SKTypeface.FromFamilyName(SKFontManager.Default.FontFamilies.FirstOrDefault(r => String.Equals("WenQuanYi Zen Hei", r) || String.Equals("Arial Unicode MS", r)) ?? SKTypeface.Default.FamilyName);

                        var value = media_id.Substring(0, 1);
                        if (value[0] < 256)
                        {
                            if (media_id.Length > 1)
                            {
                                value = media_id.Substring(0, 2);
                            }
                            value = value.ToUpper();
                        }

                        using SKFont font = new SKFont(sKTypeface, 100);
                        using SKPaint sKPaint = new SKPaint(font);
                        sKPaint.Color = SKColor.Parse("#fff");
                        sKPaint.IsAntialias = true;
                        sKPaint.TextAlign = SKTextAlign.Center;
                        templateG.DrawText(value, 100, 140, sKPaint);
                        var output = Utility.Writer(file, false);
                        image.Encode(output, SKEncodedImageFormat.Png, 80);
                        output.Close();

                    }

                    media_id = $"file://{file}";
                }

            }
            var url = new Uri(media_id);
            if (String.Equals("auto", size) == false)
            {
                System.IO.Stream stream;
                SKCodec sKCodec = null;
                SKBitmap src = null;
                if (media_id.StartsWith("file://"))
                {
                    stream = File.OpenRead(media_id.Substring(7));
                }
                else
                {
                    stream = new System.Net.Http.HttpClient().GetStreamAsync(media_id).Result;
                }

                try
                {
                    sKCodec = SKCodec.Create(stream);
                    src = SKBitmap.Decode(sKCodec);
                    if (size.Contains("*") || size.Contains("X") || size.Contains("x"))
                    {
                        var s = size.Split('*', 'x', 'X');

                        if (src.Width != Utility.IntParse(s[0].Trim(), 0) || src.Height != Utility.IntParse(s[1].Trim(), 0))
                        {
                            this.Prompt($"图片要求尺寸为{size}");
                        }

                    }
                    else
                    {
                        var s = size.Split(':');
                        if (s.Length == 1)
                        {
                            if (src.Width > Utility.IntParse(s[0].Trim(), 200))
                            {
                                this.Prompt($"图片要求宽度像素不能超过{size}");
                            }
                        }
                        else
                        {
                            if (src.Width * Utility.IntParse(s[1].Trim(), 1) != src.Height * Utility.IntParse(s[0].Trim(), 1))
                            {
                                this.Prompt($"图片要求尺寸为{size}");
                            }
                        }

                    }
                }
                finally
                {
                    stream?.Dispose();
                    sKCodec?.Dispose();
                    src?.Dispose();


                }
            }
            if (type == "none")
            {
                webr.Transfer(url, imageKey, seq);
            }
            else
            {
                webr.Transfer(url, imageKey, seq, type.ToLower());
            }
            if (String.Equals(key, "Event"))
            {
                this.Context.Send(true);
            }
            else
            {
                this.Context.UIEvent(key, this.AsyncDialog("UI", "none"), new ListItem() { Value = seq.ToString(), Text = seq.ToString() }, true);
            }
        }


    }

}